import React, { Component } from "react";
import PubSub from "pubsub-js";

export default class Search extends Component {
  search = async () => {
    const {
      keyWordElement: { value: keyWord },
    } = this;
    // this.props.updateAppState({isFirst:false,isLoading:true})
    PubSub.publish("atguigu", { isFirst: false, isLoading: true });
    //未优化
    // fetch(`api1//search/users2?q=${keyWord}`).then(
    //     (response) => {
    //       console.log("成功了");
    //       return response.json();
    //     },
    //     (error) => {
    //       return new Promise()
    //       console.log("失败了", error);
    //     }
    //   ).then(
    //     (response) => {
    //       console.log("获取数据成功了", response);
    //     },
    //     (error) => {
    //       console.log("获取数据失败了", error);
    //     }
    //   );

    //优化
    try {
      const response = await fetch(`api1//search/users2?q=${keyWord}`)
      const data = await response.json()
      PubSub.publish('atguigu',{isLoading:false,users:data.items})
    } catch (error){
      console.log('请求出错',error)
      PubSub.publish('atguigu',{isLoading:false,err:error.message})
    }

     


    //#region
    // axios.get(`api1//search/users2?q=${keyWord}`).then(
    //     response =>{
    //       // this.props.updateAppState({isLoading:false,users:response.data.items})
    //       PubSub.publish('atguigu',{isLoading:false,users:response.data.items})
    //       },
    //     error =>{
    //       // this.props.updateAppState({isLoading:false,err:error})
    //       PubSub.publish('atguigu',{isLoading:false,err:error.message})
    //       }
    // )
    //#endregion
  };

  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索github用户</h3>
        <div>
          <input
            ref={(c) => (this.keyWordElement = c)}
            type="text"
            placeholder="输入关键词进行搜索"
          />
          &nbsp;<button onClick={this.search}>搜索</button>
        </div>
      </section>
    );
  }
}
